﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class UIBattle : UIBase
{
    public static UIBattle Instance;
    public GameObject[] playerRoots;
    public UIBattleChat battleChat;
    public UIBattleLog battleLog;
    public Text textRoom;
    public GameObject train1No;
    public GameObject train2No;
    public Text text1No;
    public Text text2No;
    public Text textDealCards;
    protected override void Awake()
    {
        base.Awake();
        Instance = this;
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        Instance = null;
    }

    public override void OnButtonCloseClick()
    {
        WebSocketClient.Instance.SendMsgName(nameof(exitroom));
    }


    private DataBattleMgr _dataBattleMgr;
    public DataBattleMgr dataBattleMgr
    {
        get
        {
            return _dataBattleMgr;
        }
    }
    public void Bind(DataBattleMgr data)
    {
        _dataBattleMgr = data;
        textRoom.text = XLocalization.Get("房号:") + " " + DataPlayer.Instance.GetGroupId();
        //battleChallenge.Bind(data);
        battleChat.Bind(data);
        battleLog.Bind(data);
    }

    public void Unbind()
    {
        _dataBattleMgr = null;
        //battleChallenge.Unbind();
        battleChat.Unbind();
        battleLog.Unbind();
    }

    protected override void onVisible()
    {
        base.onVisible();
       // Facade.Instance.RegistEvent(EventID.CardTypeChange, OnHandleCardTypeChange);
        Facade.Instance.RegistNetEvent(nameof(exitroom_rsp), OnHandleExitRoomRsp);
        Facade.Instance.RegistNetEvent(nameof(notify_exam), OnHandleNotifyExam);
        Facade.Instance.RegistNetEvent(nameof(examtrain_rsp), OnHandleExamTrain);
        Facade.Instance.RegistNetEvent(nameof(notify_vote), OnHandleNotifyVote);
        Facade.Instance.RegistNetEvent(nameof(notify_voteclear), OnHandleNotifyVoteClear);
        Facade.Instance.RegistNetEvent(nameof(notify_dealcard), OnHandleNotifyDealCard);
    }

    protected override void OnInvisible()
    {
        base.OnInvisible();
       // Facade.Instance.UnRegistEvent(EventID.CardTypeChange, OnHandleCardTypeChange);
        Facade.Instance.UnRegistNetEvent(nameof(exitroom_rsp), OnHandleExitRoomRsp);
        Facade.Instance.UnRegistNetEvent(nameof(notify_exam), OnHandleNotifyExam);
        Facade.Instance.UnRegistNetEvent(nameof(examtrain_rsp), OnHandleExamTrain);
        Facade.Instance.UnRegistNetEvent(nameof(notify_vote), OnHandleNotifyVote);
        Facade.Instance.UnRegistNetEvent(nameof(notify_voteclear), OnHandleNotifyVoteClear);
        Facade.Instance.UnRegistNetEvent(nameof(notify_dealcard), OnHandleNotifyDealCard);
    }

    protected override void OnClose()
    {
        base.OnClose();
        //diceRoot.SetActive(false);

        //销毁节点
        for (int i = 0; i < playerRoots.Length; i++)
        {
            var trans = playerRoots[i].transform;
            for (int j = trans.childCount - 1; j > -1 ; j--)
            {
                XGameObject.Destroy(trans.GetChild(j).gameObject);
            } 
        }

        //清除发的卡牌
        textDealCards.text = "";

        Unbind();
    }
    //private void OnHandleCardTypeChange(object arg)
    //{
    //    Dictionary<DiceType, int> diceType2Num = new Dictionary<DiceType, int>();
    //    DiceType diceType;
    //    int num;
    //    //统计数量
    //    foreach (DataBattlePlayer dataBattlePlayer in _dataBattleMgr.userid2data.Values)
    //    {
    //        //if (dataBattlePlayer.GetState() != CardType.Open && dataBattlePlayer.GetState() != CardType.Glance)
    //        //    continue;


    //        for (int i = (int)DiceType.One; i <= (int)DiceType.Six; i++)
    //        {
    //            diceType = (DiceType)i;
    //            if(!diceType2Num.TryGetValue(diceType, out num))
    //            {
    //                num = 0;
    //            }
    //            num += dataBattlePlayer.GetDiceNum(diceType);
    //            diceType2Num[diceType] = num;
    //        }
    //    }

    //    if (diceType2Num.Count < 1)
    //    {
    //        //diceRoot.SetActive(false);
    //        return;
    //    }
    //    //diceRoot.SetActive(true);

    //    //显示出来
    //    for (int i = (int)DiceType.One; i <= (int)DiceType.Six; i++)
    //    {
    //        diceType = (DiceType)i;
    //        if (!diceType2Num.TryGetValue(diceType, out num))
    //        {
    //            _diceType2Text[diceType].text = "x0";
    //        }
    //        else
    //        {
    //            _diceType2Text[diceType].text = "x" + num;
    //        }
           
    //    }
    //}

    public void OnButtonExam1NoClick(Button button)
    {
        var req = new examtrain();
        req.type = 1;
        WebSocketClient.Instance.SendSerialize(button, req);
    }

    public void OnButtonExam2NoClick(Button button)
    {
        var req = new examtrain();
        req.type = 2;
        WebSocketClient.Instance.SendSerialize(button, req);
    }

    private void OnHandleExitRoomRsp(System.Object data)
    {
        var rsp = data as exitroom_rsp;
        if (rsp.ret == NetErrorCode.None)
        {
            SceneMgr.Instance.LoadScene(SceneName.SceneMain);
        }
        else
        {
            UITips.Instance.Show("Exit error:" + rsp.reason);
            SceneMgr.Instance.LoadScene(SceneName.SceneMain);
        }

        DataPlayer.Instance.ClearGroupId();
    }

    private void OnHandleNotifyExam(System.Object data)
    {
        var rsp = data as notify_exam;
        var dataBattleMgr = BattleCtr.Instance.dataBattleMgr;
        int unSupportNum = 0;
        foreach (var player in dataBattleMgr.userid2data.Values)
        {
            if(player.GetSupportType() == SupportType.UnSupportSecret)
            {
                unSupportNum++;
            }
        }
        train1No.SetActive(rsp.type == 1);
        train2No.SetActive(rsp.type == 2);

        //显示发车结果
        Text text = null;
        if (rsp.type == 1)
            text = text1No;
        else if (rsp.type == 2)
            text = text2No;
        else
            throw new System.Exception("unhandle type:" + rsp.type);
        if (unSupportNum >= rsp.type)
        {

            text.text = "发车\n失败";
            Debug.Log("发车失败");
        }
        else
        {
            text.text = "发车\n成功";
            Debug.Log("发车成功");
        }

        //重置标志位
        //foreach (var player in dataBattleMgr.userid2data.Values)
        //{
        //    player.SetSupportType(SupportType.Invalid);
        //}
    }

    private void OnHandleExamTrain(System.Object data)
    {
        var rsp = data as examtrain_rsp;
        if(rsp.ret != NetErrorCode.None)
        {
            UITips.Instance.Show("出错了:" + rsp.reason);
        }

        WebSocketClient.Instance.SendMsgName(nameof(voteclear));
        
    }

    //有人投票，就开始隐藏发车结果
    private void OnHandleNotifyVote(System.Object data)
    {
        train1No.SetActive(false);
        train2No.SetActive(false);
    }

    private void OnHandleNotifyVoteClear(System.Object data)
    {
        //this.OnHandleNotifyVote(null);
    }

    private void OnHandleNotifyDealCard(System.Object data)
    {
        var rsp = data as notify_dealcard;
        List<int> cardTypeList = new List<int>();
        foreach (var member_info in rsp.member_infos)
        {
            cardTypeList.Add(member_info.card_type);
        }
        //排序
        cardTypeList.Sort((a, b) => a - b);

        var sb = new System.Text.StringBuilder();
        sb.AppendLine(XLocalization.Get("发的卡牌:"));
        CardType cardType;
        foreach (var vCardType in cardTypeList)
        {
            cardType = (CardType)vCardType;
            sb.AppendLine(CardTypeHelper.GetCardTypeNameEng(cardType) + " " + CardTypeHelper.GetCardTypeNameCHS(cardType));
        }

        //显示发的卡牌
        textDealCards.text = sb.ToString();
    }
}
